package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DevicePropertiesVo;
import com.zzyl.nursing.vo.ProductVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Map;

/**
 * 设备表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-08
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    // 从物联网平台同步产品列表
    @Override
    public void syncProductList() {
        //1.去iot平台查询产品列表
        ListProductsResponse request = client.listProducts(new ListProductsRequest());
        if (request.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询产品，同步失败");
        }
        List<ProductSummary> products = request.getProducts();
        //2.放到缓存redis中
        redisCache.setCacheObject(CacheConstants.IOT_ALL_PRODUCT_KEY, JSONUtil.toJsonStr(products));
    }

    // 查询所有产品列表
    @Override
    public List<ProductVo> allPriduct() {
        String cacheObject = redisCache.getCacheObject(CacheConstants.IOT_ALL_PRODUCT_KEY);
        List<ProductVo> list = JSONUtil.toList(cacheObject, ProductVo.class);
        return list;
    }

    // 设备注册
    @Override
    public void register(DeviceDto deviceDto) {
        //1.查询设备名称是否重复
        long one = this.count(new LambdaQueryWrapper<Device>().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (one > 0) {
            throw new BaseException("该设备" + deviceDto.getDeviceName() + "已注册");
        }
        //2.查询设备标识符是否重复
        long two = this.count(new LambdaQueryWrapper<Device>().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (two > 0) {
            throw new BaseException("该设备" + deviceDto.getNodeId() + "已注册");
        }
        //3.查询同一位置是否重复
        long three = this.count(new LambdaQueryWrapper<Device>().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()));
        if (three > 0) {
            throw new BaseException("该位置已注册");
        }
        //4.iot物联网平台注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withNodeId(deviceDto.getNodeId());
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        AddDeviceResponse addDeviceResponse = client.addDevice(request);
        if (addDeviceResponse.getHttpStatusCode() != 201) {
            throw new BaseException("物联网接口-设备注册失败");
        }
        //5.保存设备信息到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(addDeviceResponse.getDeviceId());
        device.setSecret(addDeviceResponse.getAuthInfo().getSecret());
        this.save(device);

    }

    //  查询设备详情
    @Override
    public DeviceDetailVo getDeviceData(String iotId) {
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (ObjectUtils.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        if (StringUtils.isNotEmpty(response.getActiveTime())) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(response.getActiveTime(), DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
//            LocalDateTime activeTime = LocalDateTime.parse(response.getActiveTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    //  更新设备信息
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateIotDevice(DeviceDto deviceDto) {
        //1.修改iot平台
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-更新设备信息，调用失败");
        }
        //2.修改数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        this.updateById(device);
    }

    //  删除设备
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteIotDevice(String iotId) {
        //1.iot平台删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            throw new BaseException("物联网接口-删除设备，调用失败");
        }
        //2.数据库删除设备
        this.remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
    }

    //  查询设备上报信息
    @Override
    public List<DevicePropertiesVo> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询设备上报信息，调用失败");
        }
        List<DeviceShadowData> shadowList = response.getShadow();
        List<DevicePropertiesVo> propertiesVoList = new ArrayList<>();
        if (ObjectUtils.isEmpty(shadowList)) {
            return null;
        }
        JSONObject properties = JSONUtil.parseObj(shadowList.get(0).getReported().getProperties());
        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadowList.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        for (Map.Entry<String, Object> property : properties) {
            DevicePropertiesVo devicePropertiesVo = new DevicePropertiesVo();
            devicePropertiesVo.setFunctionId(property.getKey());
            devicePropertiesVo.setValue(property.getValue());
            devicePropertiesVo.setEventTime(eventTime);
            propertiesVoList.add(devicePropertiesVo);
        }

        return propertiesVoList;
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse showProductResponse = client.showProduct(request);
        if (showProductResponse.getHttpStatusCode() != 200) {
            throw new BaseException("没有该产品信息");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        return serviceCapabilities;
    }
}
